// pages/kanjia_xq/kanjia_xq.js

/**   
 * 需要一个目标日期，初始化时，先得出到当前时间还有剩余多少秒  
 * 1.将秒数换成格式化输出为XX天XX小时XX分钟XX秒 XX  
 * 2.提供一个时钟，每10ms运行一次，渲染时钟，再总ms数自减10  
 * 3.剩余的秒次为零时，return，给出tips提示说，已经截止  
 */

// pages/center/userinfo.js
var app = getApp();
var utils = require('../../../utils/shop/formatShop.js');
var WxParse = require('../../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    clock: '',
    info: [],
    userInfo: {}, //用户信息    
    Kanjia_ID: 0, //当前ID
    frist_kan_flag: true, //是否关闭第一刀弹出的信息
    right: 50, //百分比样式 
    percent: 0, //百分比

    from_user_id: 0,  // > 0 表示别人分享帮忙砍价
    help_kan_flag: true, //帮忙砍价弹窗是否关闭
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中',
    });
    if (options.ownerid) {
      app.globalData.ownerid = options.ownerid;
    }
    if (options.from_user_id) {
      this.setData({
        from_user_id: options.from_user_id
      });
    }
    if (options.Kanjia_ID) {
      this.setData({
        Kanjia_ID: options.Kanjia_ID
      });
      this.load();
    } else {
      wx.showModal({
        title: '提示',
        content: '缺少参数',
        showCancel: false,
        success: function() {
          wx.navigateBack({
            delta: 1
          })
        }
      })
    }
  },

  //页面加载
  load: function() {
    if (!app.globalData.userInfo) {
      wx.hideLoading();
      app.login('', this.load);
      return false;
    }

    // 自己不能帮自己砍价
    if (this.data.from_user_id > 0 && app.globalData.userInfo.User_ID == this.data.from_user_id) {
      this.setData({
        from_user_id: 0
      });
    }

    // 查询砍价详情
    this.get_detail();
  },

  // 查询详情 
  get_detail: function (frist_kan_flag = true, help_kan_flag = true) {
    let from_user_id = this.data.from_user_id;
    var transData = {
      act: 'get_kanjia_pro_detail',
      User_ID: from_user_id > 0 ? from_user_id : app.globalData.userInfo.User_ID,
      Kanjia_ID: this.data.Kanjia_ID,
      help_user_id: from_user_id > 0 ? app.globalData.userInfo.User_ID : 0, // 帮砍人员id
    };
    app.http_req(transData, app.globalData.init.api_url, 'POST', res => {
      if (res.errorCode == 0) {
        var info = res.data;
        if (from_user_id > 0 && info.user_kanjia_id <= 0) {
          wx.showModal({
            title: '提示',
            content: '帮砍活动已不存在',
            showCancel: false,
          });
        }

        // 修改标题
        app.setNavBarTitle(info.Product_Name);

        /**
         * 计算剩余时间，如果为0则不可砍价
         */
        var overtime = parseInt(info.Totime) - Date.parse(new Date()) / 1000;
        /**
         * 判断发起的活动是否结束
         * 1：时间已过期
         * 2：已砍到底价
         */
        info.is_over = overtime > 0 ? false : true;


        //格式化时间
        info.Totime_str = utils.formatTime('yyyy-M-d h:m:s', info.Totime);


        //处理富文本
        WxParse.wxParse('detail', 'html', info.Products_Description, this);

        //求砍后进度条百分比
        if (info.user_kanjia_id && info.user_kanjia_id > 0) {
          //计算此产品需要砍多少钱才到底价
          var max_cut_money = info.Products_PriceX;// - info.Bottom_Price;
          var percent = parseInt(info.Cur_Price * 100 / max_cut_money);
        } else {
          var percent = 100;
        }

        this.setData({
          info: info,
          percent: percent, //砍价所占百分比
          right: 6 * percent - 72, //百分比样式,进度条全长600，向左偏移半个价格标识长度（72）
          frist_kan_flag: frist_kan_flag, // 第一刀信息弹窗是否隐藏
          help_kan_flag: help_kan_flag, // 帮砍信息弹窗是否隐藏
        });

        typeof (this.interval) != "undefined" && clearInterval(this.interval);
        this.countdown();
      }

      // 结束下拉刷新
      utils.overPullDownRefresh();
    });
  },

  // 倒计时
  countdown: function () {
    this.interval = setInterval(() => {
      let over_time = parseInt(this.data.info.Totime) - Date.parse(new Date()) / 1000;
      if (over_time <= 0 || this.data.info.is_over == true) {
        this.setData({
          clock: utils.date_format(over_time * 1000, 1), //格式化时间  
          'info.is_over': false
        });
        clearInterval(this.interval);
        return;
      } else {
        // 渲染倒计时时钟  
        this.setData({
          clock: utils.date_format(over_time * 1000, 1), //格式化时间  
        });
      }
    }, 1000);
  },

  /**
   * 自己砍第一刀
   */
  first_dao: function() {
    let post_data = {
      act: 'self_kanjia',
      User_ID: app.globalData.userInfo.User_ID,
      Kanjia_ID: this.data.Kanjia_ID
    };
    app.http_req(post_data, app.globalData.init.api_url, 'POST', res => {
      if (res.errorCode == 0) {
        // 更新详情
        this.get_detail(false);
      } else {
        wx.showModal({
          title: '提示',
          content: typeof res.msg != 'undefined' ? res.msg : '砍价失败',
          showCancel: false
        });
      }
    });
  },

  //关闭第一刀信息提示
  first_cancel: function() {
    this.setData({
      frist_kan_flag: !this.data.frist_kan_flag
    })
  },

  /**
   * 购买,跳转到提交订单页面
   */
  buy: function (e) {
    wx.navigateTo({
      url: '../kanjia_tj/kanjia_tj?Kanjia_ID=' + this.data.Kanjia_ID,
    })
  },

  /**
   * 帮砍
   */
  bang_kan: function () {
    let post_data = {
      act: 'help_kanjia',
      User_ID: app.globalData.userInfo.User_ID,
      Kanjia_ID: this.data.Kanjia_ID,
      help_user_id: this.data.from_user_id
    };
    app.http_req(post_data, app.globalData.init.api_url, 'POST', res => {
      if (res.errorCode == 0) {
        // 更新详情
        this.get_detail(true, false);
      } else {
        wx.showModal({
          title: '提示',
          content: typeof res.msg != 'undefined' ? res.msg : '帮砍失败',
          showCancel: false
        });
      }
    });
  },

  //关闭帮砍信息提示
  help_cancel: function () {
    this.setData({
      help_kan_flag: !this.data.help_kan_flag
    })
  },

  // 我也要参加
  me_join () {
    wx.redirectTo({
      url: '/pages/kanjia/kanjia_xq/kanjia_xq?Kanjia_ID=' + this.data.Kanjia_ID,
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    //显示加载导航条
    wx.showNavigationBarLoading();
    //初始化数据 (防止数据重复)
    this.setData({
      clock: '',
      info: [],
      userInfo: {}, //用户信息
      frist_kan_flag: true, //是否关闭第一刀弹出的信息
      
      right: 50, //百分比样式 
      percent: 0, //百分比

      help_kan_flag: true, //帮忙砍价弹窗是否关闭
    });
    this.load();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    if (this.data.from_user_id > 0 || this.data.info.user_kanjia_id > 0) {  // 已参与砍价
      return {
        title: '帮我砍价',
        path: '/pages/kanjia/kanjia_xq/kanjia_xq' + app.share() + '&Kanjia_ID=' + this.data.Kanjia_ID + '&from_user_id=' + this.data.from_user_id > 0 ? this.data.from_user_id : app.globalData.userInfo.User_ID
      }
    } else {
      return {
        title: this.data.info.Product_Name,
        path: '/pages/kanjia/kanjia_xq/kanjia_xq' + app.share() + '&Kanjia_ID=' + this.data.Kanjia_ID
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    typeof (this.interval) != "undefined" && clearInterval(this.interval);
  }
})